import { Effect } from 'umi';
import { message } from 'antd';
import { fetchAllApi, addApi, updateApi, deleteApis } from '@/services/api';
import { querySysDict } from '@/services/system';
import { ApiItem } from '@/types/api';
import { DataItem, TradeResult } from '@/types/global';
import { BaseModelType } from './common';

export interface ApiModelState {
  apiList?: ApiItem[];
  total?: number;
  pageSize?: number;
  apiTypeData?: DataItem[],
  statusData?: DataItem[],
}

export interface ApiModelType extends BaseModelType {
  namespace: 'apis';
  state: ApiModelState;
  effects: {
    fetchApiInitParams: Effect;
    fetchAllApi: Effect;
    addApi: Effect;
    updateApi: Effect;
    deleteApis: Effect;
    unMount: Effect;
  };
  // reducers: {
  //   updateState: Reducer<ParamModelState>;
  // };
}

const ApiModel: ApiModelType = {
  namespace: 'apis',
  state: {
    apiList: [],
    total: 0,
    pageSize: 10,
    statusData: [
      {
        key: '0',
        value: '生效'
      },
      {
        key: '1',
        value: '失效'
      }
    ],
  },
  effects: {
    *fetchApiInitParams({ payload }, sagaEffects) {
      const { all, call, put } = sagaEffects;
      try {
        const [ apiTypeResponse, statusResponse ] = yield all([
          call(querySysDict, {
            dictName: 'apiType'
          }),
          call(querySysDict, {
            dictName: 'status'
          })
        ]);
        console.info(apiTypeResponse);
        console.info(statusResponse);
        const apiTypeSuccess =  apiTypeResponse.success;
        const statusSuccess =  statusResponse.success;
        if (!apiTypeSuccess || !statusSuccess) {
          if (!apiTypeSuccess) {
            message.error(`${apiTypeResponse.errorCode}:${apiTypeResponse.errorMsg}`); // 打印错误信息
          }
          if (!statusSuccess) {
            message.error(`${statusResponse.errorCode}:${statusResponse.errorMsg}`); // 打印错误信息
          }
        } else {
          // const systemData = systemResponse.result.rows;
          // const clusterData = clusterResponse.result.rows;
          const result  = {
            apiTypeData: [...apiTypeResponse.result],
            statusData: [...statusResponse.result],
          };
          console.info(result);
          yield put({ type: 'updateState', payload: result });
        }
      } catch(e) {
        console.error(e);
        message.error('数据获取失败');
      }
    },
    *fetchAllApi({ payload }, sagaEffects) {
      const { call, put } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        const response: TradeResult = yield call(fetchAllApi, payload);
        // console.log(JSON.stringify(response));
        const { success } = response;
        if (success) {
          // 通讯成功取出数据
          const { result } = response;
          // 更新表格数据
          yield put({ type: 'updateState', payload: result });
        }
      } catch(e) {
        console.info(e);
        message.error('数据获取失败'); // 打印错误信息
      }
    },
    *addApi({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        console.log(JSON.stringify(payload));
        const response: TradeResult = yield call(addApi, payload);
        // console.log(JSON.stringify(response));
        const { success } = response;
        if (success) {
          message.success('新增成功');
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.info(e);
        message.error('新增失败'); // 打印错误信息
        return false;
      }
    },
    *updateApi({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        console.log(JSON.stringify(payload));
        const response: TradeResult = yield call(updateApi, payload);
        // console.log(JSON.stringify(response));
        const { success } = response;
        if (success) {
          message.success('更新成功');
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.info(e);
        message.error('更新失败'); // 打印错误信息
        return false;
      }
    },
    *deleteApis({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        console.log(JSON.stringify(payload));
        const response: TradeResult = yield call(deleteApis, payload);
        // console.log(JSON.stringify(response));
        // yield call(delay, 3000);
        const { success } = response;
        if (success) {
          message.success('删除成功');
          // 刷新表格
          return true;
        } else {
          return false;
        }
      } catch(e) {
        console.info(e);
        message.error('删除失败'); // 打印错误信息
        return false;
      }
    },
    *unMount({ payload }, sagaEffects) {
      const { put } = sagaEffects;
      const result = {
        apiList: [],
        total: 0,
        pageSize: 10,
      }
      yield put({ type: 'updateState', payload: result });
    }
  },

  reducers: {
    updateState(state, { payload }) {
      console.info(payload);
      return {
        ...state,
        ...payload
      }
    },
  },
}

export default ApiModel;